import type React from 'react';
import { useEffect, useRef, useState } from 'react';
import popupStyles from './assets/popup.module.less';
import useSize from './hooks/useSize';
import styles from './index.module.less';
import { MapContext } from './MapContext';
import Mapless from './Mapless';
import type { MapStyle } from './Mapless/index.d';
import 'mapbox-gl/dist/mapbox-gl.css';
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '@/config/constants';

export type MapChangeEvent = 'zoom' | 'ready' | (string & {});

export type MapChangeEventArgs = {
  type: MapChangeEvent;
  target: Mapless;
  others?: Record<string, unknown>;
};

export type MapViewProps = {
  accessToken?: string;
  style?: MapStyle;
  className?: string;
  children?: React.ReactNode;
  center?: [number, number];
  zoom?: number;
  onLoad?: (map: Mapless) => void;
  onChange?: (e: MapChangeEventArgs) => void;
  resizable?: boolean;
};

const MapView: React.FC<MapViewProps> = ({
  accessToken,
  style = 'streets',
  children = null,
  center = DEFAULT_MAP_CENTER,
  zoom = DEFAULT_MAP_ZOOM,
  className = '',
  onLoad,
  onChange,
  resizable = false,
}) => {
  const mapviewRef = useRef<HTMLDivElement>(null);
  const mapContainer = useRef<HTMLDivElement>(null);
  const maplessInstanceRef = useRef<Mapless>(undefined);

  const [isMapReady, setIsMapReady] = useState(false);

  useSize({ resizable, mapviewRef, mapContainer, maplessInstanceRef });

  useEffect(() => {
    if (!mapContainer.current || maplessInstanceRef.current) return;

    if (!mapContainer.current) return;

    const instance = new Mapless(mapContainer.current, {
      accessToken,
      style,
      center,
      zoom,
      onMapInit() {
        // TODO 此处添加工具更好
        // new Lang(instance);
      },
      onMapReady() {
        maplessInstanceRef.current = instance;
        setIsMapReady(true);
        onLoad?.(instance);
        onChange?.({ type: 'ready', target: instance });
      },
      onMapZoom(zoom) {
        onChange?.({ type: 'zoom', target: instance, others: { zoom } });
      },
    });

    // resizeOnce();

    return () => {
      instance.destroy();
      maplessInstanceRef.current = undefined;
    };
  }, [accessToken]);

  return (
    <MapContext.Provider
      value={{ mapless: maplessInstanceRef.current, isMapReady }}
    >
      <div
        ref={mapviewRef}
        className={`${styles.MapView} ${popupStyles['map-popup']} ${className}`}
      >
        <div ref={mapContainer} className={`${styles.map}`} />
        {children}
      </div>
    </MapContext.Provider>
  );
};

// TODO memo
export default MapView;

export { Mapless };
